package com.example.hetong_system.service;

import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
public class AIService {

    /**
     * 获取AI回答（同步方式）
     */
    public String getAnswer(String question, Long contractId) {
        try {
            // 构建命令
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "ollama", "run", "deepseek-r1:1.5b"
            );

            // 设置环境变量和工作目录（如果需要）
            processBuilder.directory(null);
            Map<String, String> env = processBuilder.environment();
            env.put("LANG", "zh_CN.UTF-8");

            // 启动进程
            Process process = processBuilder.start();

            // 写入问题
            process.getOutputStream().write(question.getBytes());
            process.getOutputStream().flush();
            process.getOutputStream().close();

            // 读取输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 等待进程结束
            int exitCode = process.waitFor();

            if (exitCode == 0) {
                return output.toString();
            } else {
                return "⚠️ 错误：模型执行失败，退出码: " + exitCode;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return "❌ 执行异常：" + e.getMessage();
        }
    }

//    public String getAnswer(String question, Long contractId) {
//        try {
//            // 构建命令
//            ProcessBuilder processBuilder = new ProcessBuilder(
//                    "ollama", "run", "deepseek-r1:1.5b"
//            );
//
//            // 设置环境变量和工作目录（如果需要）
//            processBuilder.directory(null);
//            Map<String, String> env = processBuilder.environment();
//            env.put("LANG", "zh_CN.UTF-8");
//
//            // 启动进程
//            Process process = processBuilder.start();
//
//            // 写入问题
//            process.getOutputStream().write(question.getBytes());
//            process.getOutputStream().flush();
//            process.getOutputStream().close();
//
//            // 读取输出
//            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//            StringBuilder output = new StringBuilder();
//            String line;
//            while ((line = reader.readLine()) != null) {
//                output.append(line).append("\n");
//            }
//
//            // 等待进程结束
//            int exitCode = process.waitFor();
//
//            if (exitCode == 0) {
//                String response = output.toString();
//                // 仅处理开头的<think>标签
//                String startTag = "<think>";
//                String endTag = "</think>";
//
//                if (response.startsWith(startTag)) {
//                    int endTagIndex = response.indexOf(endTag);
//                    if (endTagIndex != -1) {
//                        // 移除从<think>到</think>的所有内容，包括标签
//                        response = response.substring(endTagIndex + endTag.length()).trim();
//                    }
//                }
//                return response;
//            } else {
//                return "⚠️ 错误：模型执行失败，退出码: " + exitCode;
//            }
//        } catch (IOException | InterruptedException e) {
//            e.printStackTrace();
//            return "❌ 执行异常：" + e.getMessage();
//        }
//    }



    /**
     * 获取AI回答（异步方式）
     */
    public CompletableFuture<String> getAnswerAsync(String question, Long contractId) {
        return CompletableFuture.supplyAsync(() -> getAnswer(question, contractId));
    }
}